//
//  SearchCityCoordinator.swift
//  CitySearch
//
//  Created by guotonglin on 2020/6/2.
//  Copyright © 2020 guotonglin. All rights reserved.
//

import Foundation
import UIKit
import RxCocoa
import RxSwift

class SearchCityCoordinator: BaseCoordinator {

    private let router: Routing
    
    private let bag = DisposeBag()

//    private let navigationController: UINavigationController
//    init(navigationController: UINavigationController) {
//        self.navigationController = navigationController
//    }
    
    init(router: Routing) {
        self.router = router
    }

    override func start() {
        // 遵守 Storyboardable 协议 都可以通过 instantiate 实例化
        let vc = SearchCityViewController.instantiate()

        // 任何 实现 SearchCitiViewPresentable 协议 都可以作为 VC 的 ViewModel ，耦合降低
        // viewModelBuilder 会传入外部输入信号
        vc.viewModelBuilder = { [bag] input in
            let model = SearchCityViewModel(input: input, airportService: AirportService.shared)
            // 订阅 cell 被点击信号 跳转到  Airport 模块
            model.router.citySelected.map({ [weak self] in
                guard let `self` = self else { return }
                self.showAirports(userModel: $0)
            })
                .drive()
                .disposed(by: bag)
            return model
        }
        self.router.push(vc, isAnimated: true, onNavigationBack: isCompleted)
    }
}

extension SearchCityCoordinator {
    func showAirports(userModel models: Set<AirportModel>) -> Void {
        let airportCoordinator = AirportCoordinator(models: models, router: self.router)
        airportCoordinator.isCompleted = { [weak self, weak airportCoordinator] in
            guard let `self` = self, let airportCoordinator = airportCoordinator else {
                return
            }
            self.remove(coordinator: airportCoordinator)
        }
        airportCoordinator.start()
        self.add(coordinator: airportCoordinator)
    }
}
